How to check that a Python function throws an exception?
How to check that a Python function throws an exception?
227
20-Jul-2023
Updated on 20-Jul-2023
Aryan Kumar
20-Jul-2023Sure, there are a few ways to check that a Python function throws an exception.
One way is to use the
assertRaises()function from theunittestmodule. TheassertRaises()function takes two arguments: the first argument is the exception that you want to check for, and the second argument is the function that you want to call.For example, the following code checks that the
divide_numbers()function throws aZeroDivisionErrorexception if the denominator is zero:Python
Another way to check that a Python function throws an exception is to use the
assert()statement. Theassert()statement takes two arguments: the first argument is the expression that you want to check, and the second argument is the error message that you want to print if the expression is false.For example, the following code checks that the
divide_numbers()function throws aZeroDivisionErrorexception if the denominator is zero:Python
Finally, you can also use the
try/exceptblock to check that a Python function throws an exception. Thetry/exceptblock is a control flow statement that allows you to execute a block of code and handle any exceptions that are raised.The following code checks that the
divide_numbers()function throws aZeroDivisionErrorexception if the denominator is zero:Python